package ssq.gamest.wolfmankill.port_android;

import java.io.IOException;

import ssq.gamest.wolfmankill.R;
import ssq.gamest.wolfmankill.WSServer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class ServerService extends Service {
  private static final int NOTIFICATION_STARTED_ID = 1;

  private NotificationManager notifyManager = null;
  public WSServer server;

  @Override
  public void onCreate() {
    super.onCreate();
    notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  }

  @Override
  public void onDestroy() {
    if (server != null) {
      try {
        server.stop();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    notifyManager.cancel(NOTIFICATION_STARTED_ID);
    notifyManager = null;
    super.onDestroy();
  }

  @Override
  public int onStartCommand(final Intent intent, int flags, int startId) {
    server = WSServer.runAndGetServer(new String[] { intent.getStringExtra("players"), String.valueOf(intent.getIntExtra("numPlayers", 0)), String.valueOf(intent.getIntExtra("serverPort", App.DEFAULT_WEBSOCKET_PORT)) });

    showNotification();
    return START_STICKY;
  }

  @Override
  public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);

  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  private void showNotification() {
    String text = "狼人杀服务器正在运行...";
    Notification notification = new Notification(R.drawable.server, text, System.currentTimeMillis());
    Intent startIntent = new Intent(this, ServerActivity.class);
    startIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(this, 0, startIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
    notification.setLatestEventInfo(this, "Gamest安卓游戏平台", "狼人杀服务器正在运行", intent);
    notifyManager.notify(NOTIFICATION_STARTED_ID, notification);
  }
}
